# -*- coding: utf-8 -*-
"""
心理咨询师服务系统 - 会员API
"""

from flask import request, jsonify, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.api.members import bp
from app.models import User, UserMembership, MembershipPlan, MembershipOrder, Scale, MemberScalePublication, Assessment
from app import db
from app.utils.helpers import success_response, error_response
from datetime import datetime, timedelta
import uuid


@bp.route('/plans', methods=['GET'])
def get_membership_plans():
    """获取会员套餐列表"""
    try:
        plans = MembershipPlan.query.filter_by(is_active=True).order_by(
            MembershipPlan.sort_order.asc()
        ).all()
        
        plan_list = []
        for plan in plans:
            plan_data = {
                'id': plan.id,
                'name': plan.name,
                'description': plan.description,
                'duration_days': plan.duration_days,
                'original_price': plan.original_price,
                'current_price': plan.current_price,
                'discount_percentage': plan.discount_percentage,
                'features': plan.features,
                'is_popular': plan.is_popular,
                'sort_order': plan.sort_order
            }
            plan_list.append(plan_data)
        
        return success_response('获取会员套餐成功', plan_list)
        
    except Exception as e:
        current_app.logger.error(f'获取会员套餐失败: {str(e)}')
        return error_response('获取会员套餐失败')


@bp.route('/status', methods=['GET'])
@jwt_required()
def get_membership_status():
    """获取用户会员状态"""
    try:
        user_id = get_jwt_identity()
        
        membership = UserMembership.query.filter_by(user_id=user_id).first()
        
        if not membership:
            return success_response('获取会员状态成功', {
                'is_member': False,
                'member_type': None,
                'expires_at': None,
                'days_remaining': 0,
                'benefits': []
            })
        
        # 计算剩余天数
        days_remaining = 0
        if membership.is_active and membership.expires_at:
            remaining = membership.expires_at - datetime.utcnow()
            days_remaining = max(0, remaining.days)
        
        # 获取会员权益
        benefits = []
        if membership.is_active:
            if membership.member_type.value == 'basic':
                benefits = [
                    '每月免费测评次数增加',
                    '专属客服支持',
                    '测评报告详细解读'
                ]
            elif membership.member_type.value == 'professional':
                benefits = [
                    '每月500次测评次数',
                    '全部标准量表',
                    '完整版+简版报告',
                    '多元常模支持',
                    '5个/月模板复制',
                    '效度检验+AI解读'
                ]
            elif membership.member_type.value == 'institution':
                benefits = [
                    '无限制测评次数',
                    '无限量表使用',
                    '全部显示模式',
                    '永久数据保存',
                    '团队协作',
                    '无限模板复制',
                    'API接口+定制服务'
                ]
            elif membership.member_type.value == 'research':
                benefits = [
                    '无限制测评次数',
                    '无限制+定制量表',
                    '科研级详细报告',
                    '永久数据保存',
                    '自建常模功能',
                    '大样本统计分析',
                    '原始数据导出',
                    '算法定制支持',
                    '专业技术支持'
                ]
        
        membership_data = {
            'is_member': membership.is_active,
            'member_type': membership.member_type.value if membership.member_type else None,
            'expires_at': membership.expires_at.isoformat() if membership.expires_at else None,
            'days_remaining': days_remaining,
            'benefits': benefits,
            'activated_at': membership.activated_at.isoformat() if membership.activated_at else None
        }
        
        return success_response('获取会员状态成功', membership_data)
        
    except Exception as e:
        current_app.logger.error(f'获取会员状态失败: {str(e)}')
        return error_response('获取会员状态失败')


@bp.route('/purchase', methods=['POST'])
@jwt_required()
def purchase_membership():
    """购买会员"""
    try:
        user_id = get_jwt_identity()
        data = request.get_json()
        
        plan_id = data.get('plan_id')
        payment_method = data.get('payment_method', 'alipay')
        
        if not plan_id:
            return error_response('请选择会员套餐')
        
        # 检查套餐是否存在
        plan = MembershipPlan.query.get(plan_id)
        if not plan or not plan.is_active:
            return error_response('会员套餐不存在或已下架')
        
        # 检查用户是否已有有效会员
        existing_membership = UserMembership.query.filter_by(
            user_id=user_id,
            is_active=True
        ).first()
        
        if existing_membership and existing_membership.expires_at > datetime.utcnow():
            return error_response('您已是会员，无需重复购买')
        
        # 创建订单
        order = MembershipOrder(
            order_no=f'MB{datetime.now().strftime("%Y%m%d%H%M%S")}{str(uuid.uuid4())[:8]}',
            user_id=user_id,
            plan_id=plan_id,
            plan_name=plan.name,
            original_price=plan.original_price,
            paid_price=plan.current_price,
            payment_method=payment_method,
            status='pending'
        )
        
        db.session.add(order)
        db.session.commit()
        
        # 这里应该调用支付接口，暂时模拟支付成功
        # 实际项目中需要集成支付宝、微信支付等
        
        # 模拟支付成功，直接激活会员
        order.status = 'paid'
        order.paid_at = datetime.utcnow()
        
        # 激活或更新会员
        if existing_membership:
            # 延长现有会员期限
            if existing_membership.expires_at > datetime.utcnow():
                existing_membership.expires_at += timedelta(days=plan.duration_days)
            else:
                existing_membership.expires_at = datetime.utcnow() + timedelta(days=plan.duration_days)
            existing_membership.is_active = True
            existing_membership.member_type = plan.member_type
        else:
            # 创建新会员
            membership = UserMembership(
                user_id=user_id,
                member_type=plan.member_type,
                activated_at=datetime.utcnow(),
                expires_at=datetime.utcnow() + timedelta(days=plan.duration_days),
                is_active=True
            )
            db.session.add(membership)
        
        db.session.commit()
        
        return success_response('购买会员成功', {
            'order_no': order.order_no,
            'plan_name': plan.name,
            'paid_price': plan.current_price,
            'expires_at': (datetime.utcnow() + timedelta(days=plan.duration_days)).isoformat()
        })
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'购买会员失败: {str(e)}')
        return error_response('购买会员失败')


@bp.route('/orders', methods=['GET'])
@jwt_required()
def get_membership_orders():
    """获取会员订单列表"""
    try:
        user_id = get_jwt_identity()
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        
        orders = MembershipOrder.query.filter_by(user_id=user_id).order_by(
            MembershipOrder.created_at.desc()
        ).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        order_list = []
        for order in orders.items:
            order_data = {
                'id': order.id,
                'order_no': order.order_no,
                'plan_name': order.plan_name,
                'original_price': order.original_price,
                'paid_price': order.paid_price,
                'payment_method': order.payment_method,
                'status': order.status,
                'created_at': order.created_at.isoformat() if order.created_at else None,
                'paid_at': order.paid_at.isoformat() if order.paid_at else None
            }
            order_list.append(order_data)
        
        result = {
            'orders': order_list,
            'pagination': {
                'page': orders.page,
                'pages': orders.pages,
                'per_page': orders.per_page,
                'total': orders.total,
                'has_next': orders.has_next,
                'has_prev': orders.has_prev
            }
        }
        
        return success_response('获取订单列表成功', result)
        
    except Exception as e:
        current_app.logger.error(f'获取订单列表失败: {str(e)}')
        return error_response('获取订单列表失败')


@bp.route('/benefits', methods=['GET'])
@jwt_required()
def get_membership_benefits():
    """获取会员权益详情"""
    try:
        user_id = get_jwt_identity()
        
        membership = UserMembership.query.filter_by(user_id=user_id).first()
        
        # 基础用户权益
        basic_benefits = {
            'free_assessments_per_month': 3,
            'detailed_reports': False,
            'customer_support': False,
            'consultation_discount': 0,
            'priority_booking': False
        }
        
        if not membership or not membership.is_active:
            return success_response('获取会员权益成功', {
                'member_type': 'free',
                'benefits': basic_benefits
            })
        
        # 会员权益
        benefits = basic_benefits.copy()
        
        if membership.member_type.value == 'basic':
            benefits.update({
                'free_assessments_per_month': 10,
                'detailed_reports': True,
                'customer_support': True,
                'consultation_discount': 10
            })
        elif membership.member_type.value == 'professional':
            benefits.update({
                'free_assessments_per_month': 500,
                'detailed_reports': True,
                'customer_support': True,
                'consultation_discount': 20,
                'ai_interpretation': True,
                'validity_check': True
            })
        elif membership.member_type.value == 'institution':
            benefits.update({
                'free_assessments_per_month': -1,  # 无限制
                'detailed_reports': True,
                'customer_support': True,
                'consultation_discount': 30,
                'team_collaboration': True,
                'api_access': True,
                'custom_service': True
            })
        elif membership.member_type.value == 'research':
            benefits.update({
                'free_assessments_per_month': -1,  # 无限制
                'detailed_reports': True,
                'customer_support': True,
                'consultation_discount': 40,
                'statistical_analysis': True,
                'raw_data_export': True,
                'algorithm_customization': True,
                'technical_support': True
            })
        
        return success_response('获取会员权益成功', {
            'member_type': membership.member_type.value,
            'benefits': benefits,
            'expires_at': membership.expires_at.isoformat() if membership.expires_at else None
        })
        
    except Exception as e:
        current_app.logger.error(f'获取会员权益失败: {str(e)}')
        return error_response('获取会员权益失败')


@bp.route('/usage', methods=['GET'])
@jwt_required()
def get_membership_usage():
    """获取会员使用情况"""
    try:
        user_id = get_jwt_identity()
        
        # 获取当月测评次数
        from sqlalchemy import func, extract
        current_month = datetime.utcnow().month
        current_year = datetime.utcnow().year
        
        from app.models import Assessment
        monthly_assessments = Assessment.query.filter(
            Assessment.user_id == user_id,
            extract('month', Assessment.created_at) == current_month,
            extract('year', Assessment.created_at) == current_year
        ).count()
        
        # 获取会员信息
        membership = UserMembership.query.filter_by(user_id=user_id).first()
        
        # 计算可用次数
        if not membership or not membership.is_active:
            available_assessments = max(0, 3 - monthly_assessments)
            total_limit = 3
        else:
            if membership.member_type.value in ['institution', 'research']:
                available_assessments = -1  # 无限制
                total_limit = -1
            elif membership.member_type.value == 'professional':
                available_assessments = max(0, 500 - monthly_assessments)
                total_limit = 500
            elif membership.member_type.value == 'basic':
                available_assessments = max(0, 50 - monthly_assessments)
                total_limit = 50
            else:
                available_assessments = max(0, 3 - monthly_assessments)
                total_limit = 3
        
        usage_data = {
            'current_month_usage': monthly_assessments,
            'available_assessments': available_assessments,
            'total_limit': total_limit,
            'is_unlimited': available_assessments == -1,
            'reset_date': f'{current_year}-{current_month + 1 if current_month < 12 else current_year + 1}-01'
        }
        
        return success_response('获取使用情况成功', usage_data)
        
    except Exception as e:
        current_app.logger.error(f'获取使用情况失败: {str(e)}')
        return error_response('获取使用情况失败')


@bp.route('/renew', methods=['POST'])
@jwt_required()
def renew_membership():
    """续费会员"""
    try:
        user_id = get_jwt_identity()
        data = request.get_json()
        
        plan_id = data.get('plan_id')
        
        if not plan_id:
            return error_response('请选择续费套餐')
        
        # 检查套餐是否存在
        plan = MembershipPlan.query.get(plan_id)
        if not plan or not plan.is_active:
            return error_response('会员套餐不存在或已下架')
        
        # 检查当前会员状态
        membership = UserMembership.query.filter_by(user_id=user_id).first()
        if not membership:
            return error_response('您还不是会员，请先购买会员')
        
        # 创建续费订单
        order = MembershipOrder(
            order_no=f'RN{datetime.now().strftime("%Y%m%d%H%M%S")}{str(uuid.uuid4())[:8]}',
            user_id=user_id,
            plan_id=plan_id,
            plan_name=f'{plan.name}(续费)',
            original_price=plan.original_price,
            paid_price=plan.current_price * 0.9,  # 续费9折优惠
            payment_method='alipay',
            status='pending'
        )
        
        db.session.add(order)
        db.session.commit()
        
        # 模拟支付成功
        order.status = 'paid'
        order.paid_at = datetime.utcnow()
        
        # 延长会员期限
        if membership.expires_at > datetime.utcnow():
            membership.expires_at += timedelta(days=plan.duration_days)
        else:
            membership.expires_at = datetime.utcnow() + timedelta(days=plan.duration_days)
        
        membership.is_active = True
        membership.member_type = plan.member_type
        
        db.session.commit()
        
        return success_response('续费成功', {
            'order_no': order.order_no,
            'plan_name': plan.name,
            'paid_price': order.paid_price,
            'expires_at': membership.expires_at.isoformat()
        })
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'续费失败: {str(e)}')
        return error_response('续费失败')


# ==================== 量表发布相关API ====================

@bp.route('/scale-publications', methods=['GET'])
@jwt_required()
def get_scale_publications():
    """获取会员的量表发布列表"""
    try:
        user_id = get_jwt_identity()
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        status = request.args.get('status')  # active, inactive
        search = request.args.get('search', '').strip()
        sort_by = request.args.get('sort_by', 'created_at')  # created_at, access_count, assessment_count
        sort_order = request.args.get('sort_order', 'desc')  # asc, desc
        
        # 构建查询
        query = MemberScalePublication.query.filter_by(member_id=user_id)
        
        # 状态筛选
        if status == 'active':
            query = query.filter_by(is_active=True)
        elif status == 'inactive':
            query = query.filter_by(is_active=False)
        
        # 搜索筛选
        if search:
            query = query.join(Scale).filter(
                db.or_(
                    Scale.title.contains(search),
                    MemberScalePublication.custom_title.contains(search)
                )
            )
        
        # 排序
        if sort_by == 'access_count':
            order_field = MemberScalePublication.access_count
        elif sort_by == 'assessment_count':
            order_field = MemberScalePublication.assessment_count
        else:
            order_field = MemberScalePublication.created_at
        
        if sort_order == 'asc':
            query = query.order_by(order_field.asc())
        else:
            query = query.order_by(order_field.desc())
        
        publications = query.paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        publication_list = []
        for pub in publications.items:
            pub_data = {
                'id': pub.id,
                'scale_id': pub.scale_id,
                'scale_title': pub.scale.title,
                'custom_title': pub.custom_title,
                'custom_description': pub.custom_description,
                'publication_token': pub.publication_token,
                'is_active': pub.is_active,
                'access_count': pub.access_count,
                'assessment_count': pub.assessment_count,
                'public_url': pub.generate_public_url(request.host_url),
                'created_at': pub.created_at.isoformat() if pub.created_at else None,
                'last_accessed_at': pub.last_accessed_at.isoformat() if pub.last_accessed_at else None
            }
            publication_list.append(pub_data)
        
        # 统计信息
        total_publications = MemberScalePublication.query.filter_by(member_id=user_id).count()
        active_publications = MemberScalePublication.query.filter_by(member_id=user_id, is_active=True).count()
        total_access = db.session.query(db.func.sum(MemberScalePublication.access_count)).filter_by(member_id=user_id).scalar() or 0
        total_assessments = db.session.query(db.func.sum(MemberScalePublication.assessment_count)).filter_by(member_id=user_id).scalar() or 0
        
        result = {
            'publications': publication_list,
            'pagination': {
                'page': publications.page,
                'pages': publications.pages,
                'per_page': publications.per_page,
                'total': publications.total,
                'has_next': publications.has_next,
                'has_prev': publications.has_prev
            },
            'statistics': {
                'total_publications': total_publications,
                'active_publications': active_publications,
                'total_access': total_access,
                'total_assessments': total_assessments
            }
        }
        
        return success_response('获取发布列表成功', result)
        
    except Exception as e:
        current_app.logger.error(f'获取发布列表失败: {str(e)}')
        return error_response('获取发布列表失败')


@bp.route('/scale-publications', methods=['POST'])
@jwt_required()
def create_scale_publication():
    """发布量表"""
    try:
        user_id = get_jwt_identity()
        data = request.get_json()
        
        scale_id = data.get('scale_id')
        custom_title = (data.get('custom_title') or '').strip()
        custom_description = (data.get('custom_description') or '').strip()
        is_active = data.get('is_active', True)
        
        if not scale_id:
            return error_response('请选择要发布的量表')
        
        # 检查量表是否存在
        scale = Scale.query.get(scale_id)
        if not scale:
            return error_response('量表不存在')
        
        # 检查量表是否已发布
        existing_publication = MemberScalePublication.query.filter_by(
            member_id=user_id,
            scale_id=scale_id
        ).first()
        
        if existing_publication:
            return error_response('该量表已发布，请勿重复发布')
        
        # 检查会员权限
        membership = UserMembership.query.filter_by(user_id=user_id).first()
        if not membership or not membership.is_active:
            return error_response('需要会员权限才能发布量表')
        
        # 创建发布记录
        publication = MemberScalePublication(
            member_id=user_id,
            scale_id=scale_id,
            publication_token=MemberScalePublication.generate_token(),
            custom_title=custom_title if custom_title else None,
            custom_description=custom_description if custom_description else None,
            is_active=is_active
        )
        
        db.session.add(publication)
        db.session.commit()
        
        result = {
            'id': publication.id,
            'publication_token': publication.publication_token,
            'public_url': publication.generate_public_url(request.host_url),
            'scale_title': scale.title,
            'custom_title': publication.custom_title,
            'is_active': publication.is_active
        }
        
        return success_response('发布量表成功', result)
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'发布量表失败: {str(e)}')
        return error_response('发布量表失败')


@bp.route('/scale-publications/<int:publication_id>', methods=['PUT'])
@jwt_required()
def update_scale_publication(publication_id):
    """更新量表发布信息"""
    try:
        user_id = get_jwt_identity()
        data = request.get_json()
        
        publication = MemberScalePublication.query.filter_by(
            id=publication_id,
            member_id=user_id
        ).first()
        
        if not publication:
            return error_response('发布记录不存在')
        
        # 更新字段
        if 'custom_title' in data:
            publication.custom_title = (data['custom_title'] or '').strip() if data['custom_title'] else None
        
        if 'custom_description' in data:
            publication.custom_description = (data['custom_description'] or '').strip() if data['custom_description'] else None
        
        if 'is_active' in data:
            publication.is_active = bool(data['is_active'])
        
        publication.updated_at = datetime.utcnow()
        db.session.commit()
        
        result = {
            'id': publication.id,
            'custom_title': publication.custom_title,
            'custom_description': publication.custom_description,
            'is_active': publication.is_active,
            'public_url': publication.generate_public_url(request.host_url)
        }
        
        return success_response('更新发布信息成功', result)
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'更新发布信息失败: {str(e)}')
        return error_response('更新发布信息失败')


@bp.route('/scale-publications/<int:publication_id>', methods=['DELETE'])
@jwt_required()
def delete_scale_publication(publication_id):
    """删除量表发布"""
    try:
        user_id = get_jwt_identity()
        
        publication = MemberScalePublication.query.filter_by(
            id=publication_id,
            member_id=user_id
        ).first()
        
        if not publication:
            return error_response('发布记录不存在')
        
        db.session.delete(publication)
        db.session.commit()
        
        return success_response('删除发布成功')
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'删除发布失败: {str(e)}')
        return error_response('删除发布失败')


@bp.route('/scale-publications/<int:publication_id>/detail', methods=['GET'])
@jwt_required()
def get_publication_detail(publication_id):
    """获取发布详情和统计数据"""
    try:
        user_id = get_jwt_identity()
        
        publication = MemberScalePublication.query.filter_by(
            id=publication_id,
            member_id=user_id
        ).first()
        
        if not publication:
            return error_response('发布记录不存在')
        
        # 获取测评记录
        assessments = Assessment.query.filter_by(
            scale_id=publication.scale_id
        ).order_by(Assessment.created_at.desc()).all()
        
        # 计算统计数据
        from app.models.assessment import AssessmentStatus
        total_assessments = len(assessments)
        completed_assessments = len([a for a in assessments if a.status == AssessmentStatus.COMPLETED])
        completion_rate = (completed_assessments / total_assessments * 100) if total_assessments > 0 else 0
        
        # 计算平均分
        completed_scores = []
        for a in assessments:
            if a.status == AssessmentStatus.COMPLETED and a.scores:
                total_score = sum(score.raw_score for score in a.scores if score.raw_score)
                completed_scores.append(total_score)
        average_score = sum(completed_scores) / len(completed_scores) if completed_scores else 0
        
        # 最近7天的访问趋势
        from sqlalchemy import func, text
        trend_data = []
        for i in range(7):
            date = datetime.utcnow().date() - timedelta(days=i)
            count = Assessment.query.filter(
                Assessment.scale_id == publication.scale_id,
                func.date(Assessment.created_at) == date
            ).count()
            trend_data.append({
                'date': date.isoformat(),
                'count': count
            })
        
        trend_data.reverse()
        
        result = {
            'id': publication.id,
            'scale_id': publication.scale_id,
            'scale': {
                'title': publication.scale.title,
                'description': publication.scale.description
            },
            'custom_title': publication.custom_title,
            'custom_description': publication.custom_description,
            'publication_token': publication.publication_token,
            'is_active': publication.is_active,
            'access_count': publication.access_count,
            'assessment_count': publication.assessment_count,
            'public_url': publication.generate_public_url(request.host_url),
            'created_at': publication.created_at.isoformat() if publication.created_at else None,
            'last_accessed_at': publication.last_accessed_at.isoformat() if publication.last_accessed_at else None,
            'statistics': {
                'total_access': publication.access_count,
                'total_assessments': total_assessments,
                'completed_assessments': completed_assessments,
                'completion_rate': round(completion_rate, 2),
                'average_score': round(average_score, 2)
            },
            'trend_data': trend_data,
            'recent_assessments': [{
                'id': a.id,
                'status': str(a.status),
                'total_score': sum(score.raw_score for score in a.scores if score.raw_score) if a.scores else 0,
                'duration': int((a.completed_at - a.created_at).total_seconds()) if a.completed_at and a.created_at else None,
                'created_at': a.created_at.isoformat() if a.created_at else None
            } for a in assessments[:10]]  # 最近10条记录
        }
        
        return success_response('获取发布详情成功', result)
        
    except Exception as e:
        current_app.logger.error(f'获取发布详情失败: {str(e)}')
        return error_response('获取发布详情失败')


@bp.route('/available-scales', methods=['GET'])
@jwt_required()
def get_available_scales():
    """获取可发布的量表列表"""
    try:
        user_id = get_jwt_identity()
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 12, type=int)
        category_id = request.args.get('category_id', type=int)
        search = request.args.get('search', '').strip()
        sort_by = request.args.get('sort_by', 'created_at')  # created_at, usage_count, title
        published_status = request.args.get('published_status')  # all, published, unpublished
        
        # 构建查询 - 只显示已发布的系统量表
        query = Scale.query.filter_by(status='PUBLISHED', is_public=True)
        
        # 分类筛选
        if category_id:
            query = query.filter_by(category_id=category_id)
        
        # 搜索筛选
        if search:
            query = query.filter(
                db.or_(
                    Scale.title.contains(search),
                    Scale.description.contains(search)
                )
            )
        
        # 排序
        if sort_by == 'usage_count':
            query = query.order_by(Scale.usage_count.desc())
        elif sort_by == 'title':
            query = query.order_by(Scale.title.asc())
        else:
            query = query.order_by(Scale.created_at.desc())
        
        scales = query.paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        # 获取用户已发布的量表ID列表
        published_scale_ids = set()
        if published_status != 'unpublished':
            published_publications = MemberScalePublication.query.filter_by(member_id=user_id).all()
            published_scale_ids = {pub.scale_id for pub in published_publications}
        
        scale_list = []
        for scale in scales.items:
            is_published = scale.id in published_scale_ids
            
            # 根据发布状态筛选
            if published_status == 'published' and not is_published:
                continue
            elif published_status == 'unpublished' and is_published:
                continue
            
            scale_data = {
                'id': scale.id,
                'title': scale.title,
                'description': scale.description,
                'category_id': scale.category_id,
                'category_name': scale.category.name if scale.category else None,
                'question_count': scale.question_count,
                'estimated_time': scale.estimated_time,
                'usage_count': scale.usage_count,
                'is_published': is_published,
                'created_at': scale.created_at.isoformat() if scale.created_at else None
            }
            scale_list.append(scale_data)
        
        result = {
            'scales': scale_list,
            'pagination': {
                'page': scales.page,
                'pages': scales.pages,
                'per_page': scales.per_page,
                'total': scales.total,
                'has_next': scales.has_next,
                'has_prev': scales.has_prev
            }
        }
        
        return success_response('获取可发布量表成功', result)
        
    except Exception as e:
        current_app.logger.error(f'获取可发布量表失败: {str(e)}')
        return error_response('获取可发布量表失败')


@bp.route('/scale-publications/<int:publication_id>/assessments', methods=['GET'])
@jwt_required()
def get_publication_assessments(publication_id):
    """获取发布的测评记录"""
    try:
        user_id = get_jwt_identity()
        
        # 获取发布记录
        publication = MemberScalePublication.query.filter_by(
            id=publication_id,
            member_id=user_id
        ).first()
        
        if not publication:
            return error_response('发布记录不存在')
        
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        status = request.args.get('status')
        
        # 构建查询 - 查找通过此发布链接进行的测评
        # 注意：这里需要在Assessment模型中添加publication_id字段来关联
        # 暂时使用scale_id进行查询，后续需要完善
        query = Assessment.query.filter_by(scale_id=publication.scale_id)
        
        # 按状态筛选
        if status:
            query = query.filter_by(status=status)
        
        # 分页查询
        assessments = query.order_by(Assessment.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        # 构建返回数据
        assessment_list = []
        for assessment in assessments.items:
            # 获取用户基本信息
            user_info = {}
            if assessment.user_id:
                from app.models import User
                user = User.query.get(assessment.user_id)
                if user:
                    user_info = {
                        'id': user.id,
                        'username': user.username,
                        'email': user.email
                    }
            
            # 计算总分数
            total_score = 0
            if assessment.scores:
                total_score = sum(score.raw_score for score in assessment.scores if score.raw_score)
            
            assessment_data = {
                'id': assessment.id,
                'user_info': user_info,
                'status': str(assessment.status),
                'total_score': total_score,
                'progress_percentage': assessment.progress_percentage,
                'started_at': assessment.started_at.isoformat() if assessment.started_at else None,
                'completed_at': assessment.completed_at.isoformat() if assessment.completed_at else None,
                'time_spent': assessment.time_spent,
                'is_anonymous': assessment.is_anonymous,
                'created_at': assessment.created_at.isoformat() if assessment.created_at else None
            }
            assessment_list.append(assessment_data)
        
        # 计算统计数据
        from app.models.assessment import AssessmentStatus
        total_assessments = Assessment.query.filter_by(scale_id=publication.scale_id).count()
        completed_assessments = Assessment.query.filter_by(
            scale_id=publication.scale_id,
            status=AssessmentStatus.COMPLETED
        ).count()
        
        # 计算平均分
        completed_scores = []
        for a in Assessment.query.filter_by(scale_id=publication.scale_id, status=AssessmentStatus.COMPLETED).all():
            if a.scores:
                total_score = sum(score.raw_score for score in a.scores if score.raw_score)
                completed_scores.append(total_score)
        average_score = sum(completed_scores) / len(completed_scores) if completed_scores else 0
        
        statistics = {
            'total_assessments': total_assessments,
            'completed_assessments': completed_assessments,
            'completion_rate': (completed_assessments / total_assessments * 100) if total_assessments > 0 else 0,
            'average_score': round(average_score, 2)
        }
        
        result = {
            'assessments': assessment_list,
            'pagination': {
                'page': assessments.page,
                'pages': assessments.pages,
                'per_page': assessments.per_page,
                'total': assessments.total,
                'has_next': assessments.has_next,
                'has_prev': assessments.has_prev
            },
            'statistics': statistics
        }
        
        return success_response('获取测评记录成功', result)
        
    except Exception as e:
        current_app.logger.error(f'获取发布测评记录失败: {str(e)}')
        return error_response('获取测评记录失败')